package proj.pt.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import proj.pt.model.Department;

public class DepartmentController extends CustomSimpleFormController {

	protected Object formBackingObject(HttpServletRequest request)
    throws Exception{
		// getting the id from the request, if it is supplied as parameter.
		// else -1 will be set.
		long id = ServletRequestUtils.getLongParameter(request, "id", -1);
		
		// if id value is greater than -1, then requesting to lead an already existing from database,
		// else create a new object.
		Department department = null;
		if(id > -1){
			// load from database
			department = getLogicProcessor().getDepartment(new Long(id));
		} //end if
		
		// there may be chance that false id has given for loading from database, and that is not present there, so  will be null;
		if(department == null)
		return new Department();
		else return department;
	}
	
		
	
	/**
	 * This method does the validation.
	 */
	protected void onBindAndValidate(HttpServletRequest request,
            Object command,
            BindException errors) throws Exception {
		
		// f no validation required, then just return from this method.
		if(!doValidate(request))return;
		
		Department department = (Department)command;
		
		// look for department Id 
		if(!StringUtils.hasLength(department.getDeptId())){
			errors.reject("departmentId.required", "Department ID required");
		} else {
			// look for department ID already exist or not.
			if(!getLogicProcessor().validateDepartmentId(department)){
				errors.reject("departmentId.exist", "Department ID exists, please enter a unique ID.");
			} //end if
		}
		
		if(!StringUtils.hasLength(department.getName())){
			errors.reject("departmentName.required", "Department Name required");
		} //end if
		
	}
	
	
	protected ModelAndView onSubmit(HttpServletRequest request,
            HttpServletResponse response,
            Object command,
            BindException errors)
     throws Exception {
		
		String action = WebUtils.getAction(request);
					
		if("action_save".equals(action)){
			getLogicProcessor().saveOrUpdateDepartment((Department)command);
		} else if("action_delete".equals(action)){
			getLogicProcessor().deleteDepartment((Department)command);
		} else if("action_cancel".equals(action)){
			// do nothing
		} else{
			// do nothing.
		} 
		
		ModelAndView  mav = new ModelAndView();
		mav.setView(new RedirectView(getSuccessURI()));
		return mav;
	} //end onSubmit
	
	
}
